package com.example.pucha_xian.Activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;

import com.example.pucha_xian.R;
import com.example.pucha_xian.common.OKHttp;
import com.example.pucha_xian.common.UserUtil;
import com.example.pucha_xian.Views.InputView;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Response;

public class LoginActivity extends BaseActivity {

    private InputView mInputPhone;
    private InputView mInputPassword;
    private String phone, password;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login1);
        mInputPhone = findViewById(R.id.input_phone);
        mInputPassword = findViewById(R.id.input_password);
        SharedPreferences preferences = getSharedPreferences("PuCha", Context.MODE_PRIVATE);
        if (preferences.contains("username") && preferences.contains("password")) {
            mInputPhone.setInputStr(preferences.getString("username", null));
            mInputPassword.setInputStr(preferences.getString("password", null));
        }
    }

    public void onCommitClick(View view) {
        phone = mInputPhone.getInputStr();
        password = mInputPassword.getInputStr();
        Log.e("AAAAAA",""+password);
        if (!UserUtil.ValidateUser(this, phone, password)) {
            return;
        }
        TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this,"权限不足！", Toast.LENGTH_LONG).show();
            return;
        }
        String deviceId = tm.getDeviceId();
        if(TextUtils.isEmpty(deviceId)){
            deviceId = Settings.System.getString(
                    this.getContentResolver(), Settings.Secure.ANDROID_ID);
        }
        checkUser(phone, password,deviceId);
    }

    public void checkUser(String phone, String password, String id) {

        OKHttp.postToken(UserUtil.login,phone,password,id,new okhttp3.Callback(){

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                //请求成功返回结果 ，如果希望返回的是字符串
                final String responseData=response.body().string();
                // 注意，此时的线程不是ui线程，
                // 如果此时我们要用返回的数据进行ui更新，操作控件，就要使用相关方法
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        // 更新UI的操作
                        Log.e("AAAAAA",""+responseData);
                        Message message = new Message();
                        message.obj = responseData;
                        handler.sendMessage(message);
                    }
                }).start();
            }

            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.e("post 请求失败","======e.getMessage()"+e.getMessage());
                //解决在子线程中调用Toast的异常情况处理
                Looper.prepare();
                Toast.makeText(LoginActivity.this,"网络出问题了!", Toast.LENGTH_SHORT).show();
                Looper.loop();
            }
        });

    }

    @SuppressLint("HandlerLeak")
    public Handler handler = new Handler(){
        @Override
        public void handleMessage(@NotNull Message msg){
            super.handleMessage(msg);
            try {
                JSONObject jsData = new JSONObject((String) msg.obj);
                if(msg.obj.toString().contains("code")){
                    if(jsData.get("code").toString().equals("0")){
                        String token = (String) jsData.get("data");
                        Log.e("AAAAAA",""+token);
                        SharedPreferences preferences = getSharedPreferences("PuCha", Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = preferences.edit();
                        editor.putString("username",phone);
                        editor.putString("password",password);
                        editor.putString("token", token);
                        editor.apply();
                        Intent intent = new Intent(LoginActivity.this, ArcgisActivity.class);
                        startActivity(intent);
                    }else {
                        Toast.makeText(LoginActivity.this, jsData.get("msg").toString(), Toast.LENGTH_LONG).show();
                    }
                }else {
                    Toast.makeText(LoginActivity.this,"用户名或密码错误", Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

}
